/**
 * 动态表单
 * @author SPY
 * @date 2020/01/16
 */

import React from 'react';
import PropTypes from 'prop-types';
import Modal from './Modal';
import Form from './Form';


class DynamicIndex extends React.Component {

    // 定义传入属性
    static propTypes = {
        fields: PropTypes.array.isRequired,
        onSubmit: PropTypes.func,
        title: PropTypes.string,
        visible: PropTypes.bool,
        confirmLoading: PropTypes.bool,
        onCancel: PropTypes.func,
        width: PropTypes.number,
        layout: PropTypes.string,
        okText: PropTypes.string,
        cancelText: PropTypes.string,
    }

    // 定义传入属性的默认值
    static defaultProps = {
        width: 1000, // modal宽度
        title: '动态表单弹窗',
        visible: true,
        onSubmit: () => { },
        onCancel: () => { },
        layout: 'vertical', // 表单布局  'horizontal'|'vertical'|'inline'
        okText: '确定',
        cancelText: '取消',
        confirmLoading: false,
    }

    // 提交Modal表单函数
    handleModalSubmit = (e) => {
        typeof e === 'object' && e.preventDefault();
        const { onSubmit } = this.props;
        this.DynamicFormRef.validateFields((err, values) => {
            if (err) return;
            if (typeof onSubmit === 'function') onSubmit(values);
        });
    }

    render() {
        const {
            fields,
            layout,
            title,
            visible,
            width,
            okText,
            cancelText,
            confirmLoading,
            onCancel,
        } = this.props;

        return (
            <Modal
                title={title}
                visible={visible}
                width={width}
                okText={okText}
                cancelText={cancelText}
                confirmLoading={confirmLoading}
                onCancel={onCancel}
                onSubmit={this.handleModalSubmit}
            >
                <Form
                    fields={fields}
                    layout={layout}
                    getForm={form => { this.DynamicFormRef = form; }}
                />
            </Modal>
        );
    }
}

export default DynamicIndex;